package cn.shopex.pay;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

import cn.shopex.pay.http.JsonRequestBean;
import cn.shopex.pay.http.JsonTask;
import cn.shopex.pay.http.JsonTaskHandler;

/**
 * Description :
 * Author : Liun
 * Date   : 2016 16/7/5 15:34.
 * Email  : liun_coolman@foxmail.com
 */

public class WeChatPayHandle {

    private Context context;
    private String paymentid;
    public String wxpaySign;
    StringBuffer sb;
    private static IWXAPI wxapi;
    private PayReq req;
    private static String appId;

    public WeChatPayHandle() {
    }

    public WeChatPayHandle(Context context) {
        this.context = context;
        sb = new StringBuffer();
        req = new PayReq();
    }


    /**
     * @param context
     * @param appid   在官网注册生成的appid
     * @return
     */
    public static IWXAPI createWXAPI(Context context, String appid) {
        wxapi = WXAPIFactory.createWXAPI(context, null);
        appId = appid;
        wxapi.registerApp(appid);
        return wxapi;
    }

    /**
     * @param info orderid      订单号
     *             total_amount 订单总金额
     *             pay_app_id   服务端返回的预支付交易会话ID
     *             token        用于发送至服务器的数据签名用
     *             method       请求获取服务器prepayid方法名,如:mobileapi.pay.weixinpay
     *             url          请求URL前缀 如:http://fenxiao.wyaopeng.com/index.php/api
     * @return
     */
    public Boolean callWXPay(WeiXinPayInfo info) {

        String orderid = info.getOrderid();
        String pay_app_id = info.getPay_app_id();
        String total_amount = info.getTotal_amount();
        String method = info.getMethod();
        String url = info.getUrl();
        String token = info.getToken();

        if (!wxapi.isWXAppInstalled() && wxapi.isWXAppSupportAPI()) {
            Toast.makeText(context, "未安装微信客户端,请安装后再试!", Toast.LENGTH_LONG).show();
            return false;
        }

        if (TextUtils.isEmpty(orderid)) {
            Toast.makeText(context, "订单信息出错了！", Toast.LENGTH_LONG).show();
            return false;
        }
        // 从服务器获取prepayid
        JsonRequestBean bean = new JsonRequestBean(method, url)
                .addParams("payment_order_id", orderid)
                .addParams("payment_cur_money", total_amount)
                .addParams("payment_pay_app_id", pay_app_id);

        Util.excuteJsonTask(new JsonTask(token), new WeiXinPayTask(bean));
        return true;
    }

    /**
     * 预存款充值：微信支付
     * @param data
     * @param method
     * @param url
     * @param token
     * @return
     */
    public boolean callWXPay(JSONObject data, String method, String url, String token) {
        boolean sIsWXAppInstalledAndSupported = wxapi.isWXAppInstalled() && wxapi.isWXAppSupportAPI();
        if (!sIsWXAppInstalledAndSupported) {
            Toast.makeText(context, "微信客户端未安装，请安装微信客户端！", Toast.LENGTH_LONG).show();
            return false;
        }

        JsonRequestBean bean = new JsonRequestBean(method, url)
                .addParams("payment_order_id", data.optString("payment_order_id"))
                .addParams("payment_cur_money", data.optString("payment_cur_money"))
                .addParams("payment_pay_app_id", data.optString("payment_pay_app_id"))
                .addParams("pay_object", data.optString("pay_object")
                );

        Util.excuteJsonTask(new JsonTask(token), new WeiXinPayTask(bean));

        return true;
    }


    public class WeiXinPayTask implements JsonTaskHandler {
        private JsonRequestBean bean;

        public WeiXinPayTask(JsonRequestBean bean) {
            this.bean = bean;
        }

        @Override
        public JsonRequestBean task_request() {
            return bean;
        }

        @Override
        public void task_response(String json_str) {

            Log.d("test", json_str);

            try {
                JSONObject all = new JSONObject(json_str);
                Log.d("task_response", all.toString());
                String prepayid = null;
                String pay_sign = null;
                String nonce_str = null;
                String timestamp = null;
                String partnerid = null;
                String apikey = null;


                JSONObject data = all.optJSONObject("data");
                prepayid = data.optString("prepayid", null);
                pay_sign = data.optString("pay_sign", null);
                nonce_str = data.optString("nonce_str", null);
                timestamp = data.optString("timestamp", null);
                partnerid = data.optString("partnerid", null);
                apikey = data.optString("api_key", null);
                paymentid = data.optString("payment_id");


                if (!TextUtils.isEmpty(prepayid) && !TextUtils.isEmpty(apikey) && !TextUtils.isEmpty(pay_sign) && !TextUtils.isEmpty(nonce_str) && !TextUtils.isEmpty(timestamp) && !TextUtils.isEmpty(partnerid)) {
                    // 开始支付
                    genPayReq(prepayid, pay_sign, nonce_str, partnerid, timestamp, apikey);// 生成参数
                    wxapi.sendReq(req);
                } else {
                    Toast.makeText(context, "服务器返回信息出错了，请重试！", Toast.LENGTH_LONG).show();
                    return;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private void genPayReq(String prepay_id, String sign, String noncestr, String partnerid, String time, String apikey) {

        req.appId = appId;
        req.partnerId = partnerid;
        req.prepayId = prepay_id;
        req.packageValue = "Sign=WXPay";
        req.nonceStr = noncestr;
        req.timeStamp = time;

        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genAppSign(signParams, apikey);

        wxpaySign = req.sign;

        sb.append("sign\n" + req.sign + "\n\n");
    }

    private String genAppSign(List<NameValuePair> params, String apikey) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(apikey);

        this.sb.append("sign str\n" + sb.toString() + "\n\n");
        String appSign = Md5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Util.debug("orion" + appSign);
        return appSign;
    }

    public String getWxpaySign() {
        return wxpaySign;
    }

    public String getPaymentid() {
        return paymentid;
    }
}
